/**
 * 
 */
package com.seguriapp.sync;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.seguriapp.communication.WebServiceConsumer;
import com.seguriapp.entities.ComplaintEntity;
import com.seguriapp.entities.MediaContentEntity;

/**
 * @author pjohnson
 * 
 */
public class ComplaintTask extends AsyncTask<Object, Boolean, Boolean> {

	private Context mContext;
	private ComplaintEntity mComplaint;

	public ComplaintTask(final Context context, ComplaintEntity complaint) {
		mContext = context;
		mComplaint = complaint;
	}

	@Override
	protected Boolean doInBackground(Object... arg0) {
		final WebServiceConsumer webServiceConsumer = WebServiceConsumer
				.getInstance(mContext);
		final JSONObject jsonComplaint = new JSONObject();

		try {
			jsonComplaint.put("names", mComplaint.getNames());
			jsonComplaint.put("lastNames", mComplaint.getLastnames());
			jsonComplaint.put("dni", mComplaint.getDni());
			jsonComplaint.put("address", mComplaint.getAddress());
			jsonComplaint.put("email", mComplaint.getMail());
			jsonComplaint.put("phone", mComplaint.getPhone());
			jsonComplaint.put("description", mComplaint.getDescription());
			jsonComplaint.put("crimelongitude", mComplaint.getCrimeLongitude());
			jsonComplaint.put("crimelatitude", mComplaint.getCrimeLatitude());
			jsonComplaint.put("complaintlongitude",
					mComplaint.getComplaintLongitude());
			jsonComplaint.put("complaintlatitude",
					mComplaint.getComplaintLatitude());
			jsonComplaint.put("crimeDate", mComplaint.getDateComplaint());
			jsonComplaint.put("categoryId", mComplaint.getCrimeCategoryId());
			jsonComplaint.put("entityId", mComplaint.getComisariaId());
			jsonComplaint.put("deviceId", 2);

			final JSONArray jSonMedia = new JSONArray();
			for (int i = 0; i < mComplaint.getMediaContentList().size(); i++) {
				final MediaContentEntity objMedia = mComplaint
						.getMediaContentList().get(i);
				final JSONObject media = new JSONObject();
				media.put("name", objMedia.getName());
				media.put("type", objMedia.getType());
				media.put("uri", objMedia.getUrl());
				jSonMedia.put(media);
			}
			jsonComplaint.put("media", jSonMedia);

		} catch (JSONException e) {
			Log.e("error Json", e.getMessage());
		}

		webServiceConsumer.sendComplaint(jsonComplaint);
		return true;
	}

	@Override
	protected void onPostExecute(final Boolean result) {
		Toast.makeText(mContext, "Denuncia Hecha", Toast.LENGTH_SHORT).show();
	}

}
